using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Topology.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Topology;

/// <summary>
/// 全览拓扑
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class TopologyService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<SpecialInstructions> _rep;

	private readonly UserManager _userManager;

	public TopologyService(SqlSugarRepository<SpecialInstructions> rep, UserManager userManager)
	{
		_rep = rep;
		_userManager = userManager;
	}

	/// <summary>
	/// huoqu
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/topology/list")]
	public async Task<dynamic> Page([FromQuery] OwnerInput input)
	{
		TopologyOutPut topologyOutPut = new TopologyOutPut
		{
			Name = _userManager.RealName,
			Code = 0,
			Lable = "",
			Children = new List<TopologyOutPut>()
		};
		var region = await (from u in _rep.Context.Queryable<Building>()
			where u.IsDelete == false
			select new { u.Name, u.Id }).ToListAsync();
		List<long> buildingId = region.Select(u => u.Id).ToList();
		var roomInfo = await (from u in _rep.Context.Queryable<Room>()
			where u.IsDelete == false && buildingId.Contains(u.BuildingId)
			select new { u.BuildingId, u.Id, u.Name }).ToListAsync();
		List<long> roomIds = roomInfo.Select(u => u.Id).ToList();
		var meterInfo = await (from u in _rep.Context.Queryable<ElectricMeter>()
			where u.IsDelete == false && roomIds.Contains(u.RoomId.Value)
			select new { u.RoomId, u.Sn, u.Name, u.GateStatus, u.SignalStatus, u.Id }).ToListAsync();
		foreach (var item in region)
		{
			TopologyOutPut topologyregion = new TopologyOutPut
			{
				Code = 1,
				Children = (from u in roomInfo
					where u.BuildingId == item.Id
					select new TopologyOutPut
					{
						Code = 2,
						Name = u.Name,
						Children = (from s in meterInfo
							where s.RoomId == u.Id
							select new TopologyOutPut
							{
								Code = 3,
								Lable = ((s.SignalStatus == 0) ? "离线" : "在线") + "  /  " + ((s.SignalStatus == 0) ? "拉闸" : "合闸"),
								Name = s.Sn + "/" + s.Name
							}).ToList()
					}).ToList(),
				Name = item.Name
			};
			topologyOutPut.Children.Add(topologyregion);
		}
		return topologyOutPut;
	}
}
